const axios = require('axios');
const wechatConfig = require('../config/wechat');

class WechatService {
  constructor() {
    this.accessToken = null;
    this.tokenExpires = 0;
  }

  // 获取Access Token
  async getAccessToken() {
    const now = Date.now();
    if (this.accessToken && now < this.tokenExpires) {
      return this.accessToken;
    }

    const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${wechatConfig.appId}&secret=${wechatConfig.appSecret}`;
    
    try {
      const response = await axios.get(url);
      const { access_token, expires_in } = response.data;
      
      this.accessToken = access_token;
      this.tokenExpires = now + (expires_in - 60) * 1000; // 提前60秒过期
      
      return access_token;
    } catch (error) {
      console.error('获取Access Token失败:', error.response.data);
      throw error;
    }
  }

  // 获取用户信息
  async getUserInfo(openid) {
    const accessToken = await this.getAccessToken();
    const url = `https://api.weixin.qq.com/cgi-bin/user/info?access_token=${accessToken}&openid=${openid}&lang=zh_CN`;
    
    try {
      const response = await axios.get(url);
      return response.data;
    } catch (error) {
      console.error('获取用户信息失败:', error.response.data);
      throw error;
    }
  }

  // 发送客服消息
  async sendCustomMessage(openid, message) {
    const accessToken = await this.getAccessToken();
    const url = `https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=${accessToken}`;
    
    const data = {
      touser: openid,
      msgtype: 'text',
      text: {
        content: message
      }
    };
    
    try {
      const response = await axios.post(url, data);
      return response.data;
    } catch (error) {
      console.error('发送客服消息失败:', error.response.data);
      throw error;
    }
  }

  // 创建菜单
  async createMenu(menuData) {
    const accessToken = await this.getAccessToken();
    const url = `https://api.weixin.qq.com/cgi-bin/menu/create?access_token=${accessToken}`;
    
    try {
      const response = await axios.post(url, menuData);
      return response.data;
    } catch (error) {
      console.error('创建菜单失败:', error.response.data);
      throw error;
    }
  }
}

module.exports = new WechatService();